<template>


  <el-drawer title="短信发送" :visible.sync="visible" :with-header="false" size="650px">
    <!-- 手动添加 -->
    <el-dialog width="400px" title="输入接收方手机号码,用逗号分开" :visible.sync="userPhoneDialogVisible" :close-on-click-modal="false"
      :close-on-press-escape="false" :append-to-body="true" :modal-append-to-body="false" @close='closeUserPhone'>

      <div class="flex-column justify-center align-center">
        <!-- //textarea输入框 -->
        <el-input v-model="phoneStr" type="textarea" :rows="4" placeholder="输入接收方手机号码,用逗号分开"></el-input>
        <!-- //保存按钮 -->
        <div class="flex justify-center margin-top-sm">
          <el-button type="primary" @click="saveUserPhone">保存</el-button>
        </div>

      </div>
    </el-dialog>

    <!--      选择会员-->
    <el-drawer size="650px" :with-header="false" :append-to-body="true" :visible.sync="innerDrawer">
      <div class="right-container">
        <div class="container-header">
          <div style="font-size: 14px">选择会员</div>
          <div @click="handleInnerClose">
            <i class="el-icon-close" style="font-size: 18px"></i>
          </div>
        </div>
        <div class="container-content background-color-grey padding-10">
          <div  class="background-color-white padding-10 flex-column flex justify-between align-center">
            <div class="flex justify-between">
            <el-form :inline="true" :model="serchMemberForm">
              <el-form-item label="客户名称">
                <el-input style="width: 200px;" v-model="serchMemberForm.username" placeholder="" clearable></el-input>
              </el-form-item>
              <el-form-item label="联系电话">
                <el-input style="width: 200px;" v-model="serchMemberForm.phone" placeholder="" clearable></el-input>
              </el-form-item>
              <el-form-item label="学期学年">
                <el-select style="width: 200px;" v-model="serchMemberForm.studyId" placeholder="学期学年">
                  <el-option v-for="item in studyOptions" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="课程类型">
                <el-select style="width: 200px;" v-model="serchMemberForm.type" placeholder="课程类型" >
                  <el-option
                    v-for="item in typeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="支付状态">
                <el-select style="width: 200px;" v-model="serchMemberForm.paymentStatus" placeholder="">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="下单日期">
                <el-date-picker
            v-model="orderDate"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
              </el-form-item>
            </el-form>
            </div>
            <div class="flex justify-between align-center">
              <el-button @click="getMamberList()" type="primary">查询</el-button>
            </div>
          </div>


          <div class="background-color-white padding-10 margin-top-sm">
            <el-table
              ref="memberTableRef"
              @selection-change="selectionChangeHandleMember"
             :header-cell-style="tableHeaderStyle" :data="memberList"  border
              v-loading="dataListMemberLoading"  style="width: 100%;margin-bottom:6px">
              <el-table-column
      type="selection"
      width="55">
    </el-table-column>
              <el-table-column prop="userName" label="名称" align="center" header-align="center"> </el-table-column>
              <el-table-column prop="userPhone" label="电话" align="center" header-align="center"> </el-table-column>
              <el-table-column prop="" label="操作" align="center" header-align="center" width="100" >
                 <template slot-scope="scope">
                  <el-button type="text" size="mini" @click="selectMember(scope.row)">选择</el-button>
                 </template>
              </el-table-column>
            </el-table>

            <el-pagination @size-change="sizeChangeHandleMember" @current-change="currentChangeHandleMember"
              :current-page="pageIndexMember" :page-sizes="[10, 20, 50, 100]" :page-size="pageSizeMember" :total="totalPageMember"
              layout="total, sizes, prev, pager, next, jumper">
            </el-pagination>

          </div>
        </div>
        <div class="flex justify-center padding-10">
          <el-button type="primary" @click="selectMemberListSure()">确定选择</el-button>
        </div>
      </div>
    </el-drawer>


    <div class="right-container">
      <div class="container-header">
        <div style="font-size: 14px">短信发送</div>
        <div @click="handleClose">
          <i class="el-icon-close" style="font-size: 18px"></i>
        </div>
      </div>
      <div class="container-content background-color-grey padding-10">
        <div class="bg-white border-radius">
          <div class="flex justify-between align-center margin-bottom-sm padding-lg border-bottom card-heard-title ">
            <div>
              <i class="el-icon-collection-tag" style="font-size: 18px"></i>
              模版选择
            </div>
          </div>
          <div class="padding-lg">
            <el-form :model="dataForm" @keyup.enter.native="getDataList()">
              <el-form-item label="短信签名" prop="signName" :rules="[{ required: true, message: '请选择短信签名', trigger: 'blur' }]">
                <el-select class="selectWidth"  v-model="dataForm.signName" placeholder="">
                  <el-option v-for="item in signDataListOptaions" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select> </el-form-item>
              <el-form-item label="短信模板" prop="templateCode" :rules="[{ required: true, message: '请选择短信模板', trigger: 'blur' }]">
                <el-select class="selectWidth" @change="changeTemplate" v-model="dataForm.templateCode" placeholder="">
                  <el-option v-for="item in templateDataListOptaions" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="模版预览">
                  {{dataForm.templateContent }}
              </el-form-item>
            </el-form>
          </div>


        </div>

        <div class="bg-white border-radius margin-top-md">
          <div class="flex justify-between align-center margin-bottom-sm padding-lg border-bottom card-heard-title">
            <div>
              <i class="el-icon-collection-tag" style="font-size: 18px"></i>
              接收人
            </div>
          </div>
          <div class="padding-lr-lg padding-bottom-lg">

            <div class="flex margin-tb-sm" style="flex-direction: row-reverse;">
              <div class="margin-left-sm">
                <el-button type="primary" size="mini" @click="openUserPhone()">手动添加</el-button>
              </div>

              <div>
                <el-button type="primary" size="mini" @click="openInner()">选择会员</el-button>
              </div>
            </div>
            <el-table ref="tableRef" :header-cell-style="tableHeaderStyle" :data="dataList" border style="width: 100%;">
              <!-- //序号 取index+1 -->
              <el-table-column prop="id" label="序号" width="60" align="center">
                <template slot-scope="scope">
                  <span>{{ scope.$index + 1 }}</span>
                </template>
              </el-table-column>

              <el-table-column prop="userPhone" header-align="left" align="left" label="电话">
              </el-table-column>

              <el-table-column prop="userName" header-align="left" align="left" label="姓名">
              </el-table-column>


              <el-table-column prop="myselfAns" header-align="left" align="left" label="操作" width="100">
                <template slot-scope="scope">
                  <el-button type="text" size="mini" @click="deleteDataList(scope.row,scope.$index)">删除</el-button>
                </template>
              </el-table-column>

            </el-table>

          </div>
        </div>

        <div class="flex justify-center padding-10">
          <el-button type="primary" @click="sendCodeToUser()">发送</el-button>
        </div>
      </div>
    </div>

  </el-drawer>
</template>

<script>

export default {
  name: 'sendcode',
  data() {
    return {
      studyOptions: [
        {
          value: '',
          label: '请选择'
        },
      ],
      serchMemberForm:{
        username:"",
        phone:"",
        type:'',
        studyId:"",
        startDate:"",
        endDate:"",
        paymentStatus:""

      },
      orderDate:"",
      options: [{
          value: '2',
          label: '已支付'
        }, {
          value: '0',
          label: '支付中'
        }, {
          value: '4',
          label: '已退款'
        }],
        typeOptions:[
          {
            value: '',
            label: '请选择'
          },{
            value: 0,
            label: '专业科目'
          }, {
            value: 1,
            label: '公需科目'
          }
        ],
      innerDrawer:false,
      userPhoneDialogVisible: false,
      dataForm: {
        signName: '',
        templateCode: '',
        userList: []
      },
      manageItem: {
        name: '',
        studyName: ''
      },
      signDataListOptaions:[],
      templateDataListOptaions:[],
      templateList:[],

      tableHeaderStyle: { background: '#f5f7fa !important', height: '20px !important', padding: '4px !important' },
      direction: 'rtl',
      visible: false,
      dataList: [],
      selectMemberList:[],
      dataListMemberLoading:false,
      memberList:[],
      pageIndexMember: 1,
      pageSizeMember: 10,
      totalPageMember: 0,
      phoneStr:"",
    }
  },
  mounted() {
    this.getstudyOptionsList()
  },
  created() {
  },
  methods: {
    //获取学期学年数据
    getstudyOptionsList() {
      this.$http({
        url: this.$http.adornUrl('/class/study/list'),
        method: 'get',
        params: this.$http.adornParams({
          'page': 1,
          'limit': 9999999
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          if (data.page.list && data.page.list.length > 0) {
            for (let i = 0; i < data.page.list.length; i++) {
              this.studyOptions.push({
                value: data.page.list[i].id,
                label: data.page.list[i].name
              })
            }
          }
        }
      })
    },
    selectionChangeHandleMember(item){
      this.selectMemberList = item
    },
    selectMemberListSure(){
      if (this.selectMemberList.length == 0) {
        this.$message.error('请选择会员')
        return
      }
      //for循环嗲用selectMember
      this.selectMemberList.forEach((value, index) => {
        console.log(value)

        this.selectMember(value)
      })
      this.handleInnerClose();



    },
    // 每页数
    sizeChangeHandleMember(val) {
      this.pageSizeMember = val
      this.pageIndexMember = 1
      this.getMamberList()
    },
    // 当前页
    currentChangeHandleMember(val) {
      this.pageIndexMember = val
      this.getMamberList()
    },
    sendCodeToUser(){

      //短信签名和短信模板必须选择
      if (!this.dataForm.signName) {
        this.$message.error('请选择短信签名')
        return
      }
      if (!this.dataForm.templateCode) {
        this.$message.error('请选择短信模板')
        return
      }
      if (this.dataList.length == 0) {
        this.$message.error('请选择接收人')
        return
      }
      console.log(this.dataList)
      console.log(this.dataForm)
      ///sys/sms/send
      this.$http({
        url: this.$http.adornUrl('/sys/sms/send'),
        method: 'post',
        data: this.$http.adornData({
          "signName": this.dataForm.signName,
          "templateCode": this.dataForm.templateCode,
          "userList": this.dataList
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: '发送成功',
            type: 'success'
          })
          this.handleClose()

        }
      })

    },
    saveUserPhone(){
      //判断电话是否为空
      if (!this.phoneStr) {
        this.$message.error('电话不能为空')
        return
      }
      //先去空格，再将中文，替换为,
      this.phoneStr = this.phoneStr.replace(/\s+/g, "").replace(/，+/g, ",")
      //用逗号分割
      var phoneList = this.phoneStr.split(",")
      //循环添加
      phoneList.forEach((value, index) => {
        //过滤掉已经存在的
        if (!this.dataList.some(item => item.userPhone == value)) {
          this.dataList.push({
            userPhone: value,
            userName:''
          })
        }
      })
      this.closeUserPhone();

    },
    deleteDataList(item,index){
      this.dataList.splice(index,1)
    },
    selectMember(item){
      // 电话号判断是否已经存在
      if (this.dataList.some(value => item.userPhone == value.userPhone)) {
        return
      }
      this.dataList.push({
        userName:item.userName,
        userPhone:item.userPhone
      })
      this.handleInnerClose();

    },
    changeTemplate(){
      console.log(this.dataForm.templateCode)
      console.log(this.templateDataListOptaions)
      //根据模版id获取模版预览
      this.templateList.forEach((value, index) => {
        if (value.templateCode == this.dataForm.templateCode) {
          this.dataForm.templateContent = value.templateContent
        }
      })


    },
    handleInnerClose(){
      this.innerDrawer = false;
    },
    openInner(){
      this.innerDrawer = true;
      
      this.getMamberList();
    },
    initSerchMemberForm(){
      this.serchMemberForm={
        username:"",
        phone:"",
        type:'',
        studyId:"",
        startDate:"",
        endDate:"",
        paymentStatus:""
      }
    },
    closeUserPhone() {
      this.userPhoneDialogVisible = false
    },
    openUserPhone() {
      this.userPhoneDialogVisible = true
    },
    repairTableByRef(refName) {
      this.$refs[refName].doLayout()
    },
    handleClose() {
      this.visible = false; // 关闭外层 Drawer 时不关闭内层 Drawer
    },

    getMamberList(){
      this.dataListMemberLoading=true;
      this.$http({
        url: this.$http.adornUrl('/sys/userToken/list'),
        method: 'get',
        params: this.$http.adornParams({
          'page': this.pageIndexMember,
          'limit': this.pageSizeMember,
          'username':this.serchMemberForm.username,
          'phone':this.serchMemberForm.phone,
          'type': this.serchMemberForm.type,
          'studyId': this.serchMemberForm.studyId,
          'paymentStatus': this.serchMemberForm.paymentStatus,
          'startDate': this.orderDate && this.orderDate.length > 0 ? this.orderDate[0] + " 00:00:00" : "",
          'endDate': this.orderDate && this.orderDate.length > 0 ? this.orderDate[1] + " 23:59:59" : "",
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.memberList = data.page.list
          this.totalPageMember = data.page.totalCount
        } else {
          this.memberList = []
          this.totalPageMember = 0
        }
        this.repairTableByRef("memberTableRef")
        this.dataListMemberLoading = false
      })
    },
    //获取短信签名列表
 getSignDataList() {
      this.signDataListOptaions = [
        {
          value: '',
          label: '请选择'
        }
      ]
      this.$http({
        url: this.$http.adornUrl('/sys/sms/sign/list'),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({ data }) => {
        if (data && data.code === 0) {
          if(data.json&&data.json.length>0){
            //处理成下拉格式signDataListOptaions
            data.json.forEach(item => {
              this.signDataListOptaions.push({
                value: item.name,
                label: item.name
              })
            });

          }
        }
      })
    },
    //获取短信模板列表
    getTemplateDataList() {
      this.templateDataListOptaions = [
        {
          value: '',
          label: '请选择'
        }
      ]
      let search = {
        'page': 1,
        'limit': 9999999,
      }
      this.$http({
        url: this.$http.adornUrl('/sys/sms/template/list'),
        method: 'get',
        params: this.$http.adornParams(search)
      }).then(({ data }) => {
        if (data && data.code === 0) {
          if(data.page.list&&data.page.list.length>0){
            this.templateList = data.page.list;
            //处理成下拉格式signDataListOptaions
            data.page.list.forEach(item => {
              this.templateDataListOptaions.push({
                value: item.templateCode,
                label: item.templateName
              })
            });

          }

        }
      })
    },


    init(manageItem) {
      console.log(manageItem);
      this.manageItem = manageItem;
      this.visible = true;
      this.getSignDataList();
      this.getTemplateDataList();
    },
  }
}
</script>
<style>
.right-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.container-header {
  height: 50px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px
}

.container-content {
  flex: 1;
}


.flex-container {
  display: flex;
  justify-content: space-between;
  /* 根据需要调整 */
}

.flex-item {
  flex: 1;
  /* 可以根据需要调整比例 */
  margin: 0 10px;
  /* 添加一些间距 */
}

.left-panel,
.right-panel {
  /* 在这里添加任何特定的样式，比如背景色、边框等 */
}

.el-tabs--border-card>.el-tabs__content {
  padding: 10px 0;
}
</style>
